package com.soulapp.hook.hooker

import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.materialswitch.MaterialSwitch
import com.highcapable.kavaref.KavaRef.Companion.resolve
import com.highcapable.yukihookapi.hook.core.YukiMemberHookCreator.MemberHookCreator.Result
import com.highcapable.yukihookapi.hook.factory.applyModuleTheme
import com.highcapable.yukihookapi.hook.factory.injectModuleAppResources
import com.soulapp.data.ConfigData
import com.soulapp.data.bean.SettingItem
import com.soulapp.hook.R
import com.soulapp.hook.databinding.DialogSettingsBinding


object SoulMenuHook : BaseHooker() {
    private const val TAG = "SoulMenuHook"
    private var hook: Result? = null
    override fun getKey() = ConfigData.limitChat

    override fun onHook() {
        startHook()
    }

    override fun startHook() {
        // LOWPEAK_VOICEMATCH_POPUPWINDOW
        val className = "cn.soulapp.android.component.startup.main.HeavenFragment\$m"
        hook = className.toClass()
            .resolve()
            .firstMethod {
                name == "onDoubleClick"
                parameters(View::class)
                returnType == Void::class.javaPrimitiveType
            }.hook {
                after {
                    val view = args.first() as View
                    val context = view.context

                    context.injectModuleAppResources()
                    Handler(Looper.getMainLooper()).post {
                        showSettingsDialog(context)
                    }
                }
            }
    }

    private fun showSettingsDialog(context: Context) {
        // ✅ 使用 applyModuleTheme 包装 context，注入 AppCompat 主题
        val themedContext = context.applyModuleTheme(R.style.AppTheme)
        val binding = DialogSettingsBinding.inflate(LayoutInflater.from(themedContext))
        val dialogView = binding.root
        val container = binding.container

        val dataList = buildData()

        dataList.forEach { item ->
            // 创建外层 LinearLayout 容器
            val itemContainer = LinearLayout(context).apply {
                orientation = LinearLayout.HORIZONTAL
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT
                )

                // 使用 Material Design 的波纹效果
                background = getMaterialSelectableBackground(themedContext)

                // 设置可点击和焦点属性
                isClickable = true
                isFocusable = true

                // 在容器上设置点击监听器，而不是在textView上
                item.hooker.clickListener?.let { listener ->
                    setOnClickListener { view ->
                        listener.invoke(context)
                    }
                }
            }

            // 创建 TextView
            val textView = TextView(themedContext).apply {
                id = View.generateViewId()
                text = item.name
                textSize = 16f
                layoutParams = LinearLayout.LayoutParams(
                    0,
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    1f // 权重为1
                )
                // textView不需要点击监听器，点击事件由父容器处理
                // 但需要设置为不可点击，避免干扰父容器的点击事件
                isClickable = false
                isFocusable = false
            }

            // 创建 MaterialSwitch
            val switch = MaterialSwitch(themedContext).apply {
                // 生成唯一ID
                id = View.generateViewId()
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )

                // text = item.name
                // textSize = 16f
                isChecked = item.enabled
                // if (item.hooker == null) {
                //     isEnabled = false
                //     isClickable = false
                // }

                setOnCheckedChangeListener { _, isChecked ->
                    item.hooker.hookEnabled = isChecked
                }
            }

            itemContainer.addView(textView)
            itemContainer.addView(switch)
            container.addView(itemContainer)
        }

        MaterialAlertDialogBuilder(themedContext)
            .setView(dialogView)
            .show()
    }

    // 获取 Material Design 风格的可选择背景
    private fun getMaterialSelectableBackground(context: Context): Drawable? {
        val typedArray = context.obtainStyledAttributes(
            intArrayOf(android.R.attr.selectableItemBackground)
        )
        val background = typedArray.getDrawable(0)
        typedArray.recycle()
        return background
    }

    fun buildData(): List<SettingItem> {
        val dataList = arrayListOf(
            SettingItem("显示Toast提醒", ShowToastHook),

            SettingItem("去除开屏广告", LimitAdvertHook, "去除启动页广告"),
            SettingItem("信息可随时撤回", CanRecallHook),
            SettingItem("无水印下载视频图片", WatermarkHook, "聊天/广场/瞬间 图片视频去水印"),
            SettingItem("解除聊天送礼物", LimitChatHook, "去除第一次和对方聊天，显示必须要送礼物"),
            SettingItem("修改瞬间匹配年龄", MomentAgeHook),
            SettingItem("解除社交能力限制", LimitSocietyHook),
            SettingItem("解除截图限制", LimitCaptureHook),
            SettingItem("骰子猜拳作弊", DiceRockGameHook),
            // SettingItem("禁止回执消息", LimitMsgStateHook),
            // SettingItem("图片禁止销毁", RowSnapImageHook),

            // SettingItem("开启聊天气泡", null),
            // SettingItem("禁止自动更新", AutoUpdateHook),
            // SettingItem("图片阅后即焚", LimitSnapChatHook),
            // SettingItem("禁止青少年弹窗", null),
            // SettingItem("自定义金币(本地)", null),
            // SettingItem("自定义关注被关注数(本地)", FollowHook)
        )

        return dataList
    }

    override fun stopHook() {
    }
}